var rest = require('restler');
var http = require('http');
var querystring = require('querystring');

// dev core server
// var HOST = 'http://101.201.111.4:8080/';
//var HOST = 'http://192.168.1.213:8080/';
var HOST = 'http://127.0.0.1:8080/';
var DOMAIN = "127.0.0.1";
var PORT = "8080";

function parseUrl(url, data) {
  var arr = url.split('/');
  for (var i in arr) {
    var it = arr[i];
    if (it.indexOf(':') == 0) {
      arr[i] = data.urlData[it.substring(1)];
    }
  }
  return arr.join('/');
}

var ezapi = module.exports = {

  API: {
    'company_info': {
      url: 'company/:id',
      method: 'get',
      desc: ''
    }
  },

  requestStream: function (url, res) {
    // eg: return ApiService.requestStream('......', res);
    var al = HOST + url;
    console.log(al)
    http.get(al, function (response) {
      if (response.statusCode != 200) {
        // console.log(response.statusCode);
        return res.serverError(response.statusCode);
      }
      response.on('data', function (chunk) {
        res.write(chunk);
      });
      response.on('end', function () {
        return res.end();
      });
    }).on('error', function (e) {
      return res.serverError(e);
    });
  },

  requestFile: function (url, param, fileName, res) {
    var postData = querystring.stringify(param);
    var al = HOST + url;
    res.setHeader("Content-Type", "multipart/form-data;charset=utf-8");
    res.setHeader("Content-Disposition", "attachment;fileName=" + encodeURI(fileName));
    var ctx;
    var option = {
        host: DOMAIN,
        port: PORT,
        path: url,
        method: "POST",
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(postData)
        }
    };
    var reqFile = http.request(option, (response) =>  {
      if (response.statusCode != 200) {
        // console.log(response.statusCode);
        return res.serverError(response.statusCode);
      }
      response.on('data', function (chunk) {
        res.write(chunk);
      });
      response.on('end', function () {
        return res.end();
      });
    }).on('error', function (e) {
      return res.serverError(e);
    });
    reqFile.write(postData);
    reqFile.end();
  },

  request: function (api, data, cb) {
    function callback(data, response) {
      if (data.status != null && data.status == '500') {
        sails.log.error(data);
        //server error
        return cb({
          code: 500
        }, null);
      } else if (data.status != null && data.status == '400') {
        sails.log.error(data);
        return cb({
          code: 400
        }, null);
      } else {
        cb(data, response);
      }
    }

    var url = HOST + parseUrl(api.url, data);
    if (api.method == 'get') {
      ezapi.get(url, data.data, callback);
    } else if (api.method == 'post') {
      ezapi.post(url, data.data, callback);
    } else if (api.method == 'postJson') {
      ezapi.postJson(url, data.data, callback);
    } else if (api.method == 'put') {
      ezapi.put(url, data.data, callback);
    } else if (api.method == 'putJson') {
      ezapi.putJson(url, data.data, callback);
    } else if (api.method == 'del') {
      ezapi.del(url, data.data, callback);
    }
  },

  'get': function (url, json, cb) {
    sails.log(url);
    rest.get(url, {timeout: 10000}).on('timeout', function (ms) {
      cb(null);
    }).on('complete', cb);
  },

  'post': function (url, data, cb) {
    sails.log('restful api url: ' + url);
    if (data) {
      sails.log('       & data:' + JSON.stringify(data));
    }
    rest.post(url, {
      data: data
    }).on('complete', cb);
  },
  postJson: function (url, json, cb) {
    rest.postJson(url, json).on('complete', cb);
  },

  'put': function (url, data, cb) {
    sails.log(url);
    sails.log(data);
    rest.put(url, {
      data: data
    }).on('complete', cb);
  },
  'putJson': function (url, json, cb) {
    rest.putJson(url, json).on('complete', cb);
  },
  'del': function (url, json, cb) {
    sails.log(url);
    sails.log(json);
    rest.del(url, json).on('complete', cb);
  }
};
//
//ezapi.request(ezapi.API.company_info, {
//  id: 1
//}, function (data, res) {
//  sails.log(data)
//});
//
//var x = parseUrl('com/:id', {
//  id: 23
//});
//sails.log(x);
